package org.siming.generator.generator;

import org.apache.commons.lang3.StringUtils;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.internal.DefaultCommentGenerator;
import org.siming.generator.processors.AnnotationProcessor;
import org.siming.generator.processors.BaseAnnotationProcessor;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: yesiming
 * @Platform: Mac
 * @Date: 12:42 下午 2021/5/18
 *
 * 1. 是否依赖了lombok
 *  1.1 依赖：使用@Data，注解
 *  1.2 没依赖：使用get set方法
 *
 */
public class AnnotationMybatisGenerator extends DefaultCommentGenerator {

    public AnnotationMybatisGenerator() throws Exception {
        String thisName = this.getClass().getSimpleName();
        AnnotationProcessor.thisNameTL.set(thisName);
        BaseAnnotationProcessor baseAnnotationProcessor = new BaseAnnotationProcessor() {
            @Override
            public void process(TopLevelClass topLevelClass) throws Exception {

            }
        };
        baseAnnotationProcessor.loadConfigKey();

    }

    @Override
    public void addModelClassComment(TopLevelClass topLevelClass,
                                     IntrospectedTable introspectedTable) {

        // 生成基础注释
        commentGenerator(topLevelClass, introspectedTable);

        // 生成自定义注解
        AnnotationProcessor.annotationProcessorSet.forEach(c -> {
            try {
                c.process(topLevelClass);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

    }

    private void commentGenerator(TopLevelClass topLevelClass,
                                  IntrospectedTable introspectedTable) {
        topLevelClass.addJavaDocLine("/**");
        topLevelClass.addJavaDocLine(" * 自定义生成器，v1.0");

        StringBuilder sb = new StringBuilder();
        sb.append(" * 表: ");
        sb.append(introspectedTable.getFullyQualifiedTable());
        topLevelClass.addJavaDocLine(sb.toString());

        String tableRemarks = introspectedTable.getRemarks();
        if (!StringUtils.isEmpty(tableRemarks)) {
            sb.setLength(0);
            sb.append(" * 表注释 : ");
            sb.append(tableRemarks);
            topLevelClass.addJavaDocLine(sb.toString());
        }

        sb.setLength(0);
        sb.append(" * @author ");
//        sb.append(systemPro.getProperty("user.name"));
        sb.append("作者: 请自行改成通过配置文件，或者环境变量读取");
        topLevelClass.addJavaDocLine(sb.toString());

        String curDateString = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date());
        sb.setLength(0);
        sb.append(" * @date ");
        sb.append(curDateString);
        topLevelClass.addJavaDocLine(sb.toString());

        topLevelClass.addJavaDocLine(" */");
    }

}
